package com.hl.ruoyicsmshop.controller;

import com.hl.ruoyicsmshop.service.ICustomerServiceService;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.core.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 客服系统Controller
 * 
 * @author hl
 * @date 2024-01-01
 */
@RestController
@RequestMapping("/customer-service")
public class CustomerServiceController extends BaseController {
    
    @Autowired
    private ICustomerServiceService customerServiceService;
    
    /**
     * 测试接口 - 验证服务是否正常运行
     */
    @GetMapping("/test")
    public AjaxResult test() {
        return AjaxResult.success("客服服务正常运行");
    }
    
    /**
     * 创建客服会话
     */
    @PostMapping("/session/create")
    @Log(title = "客服会话", businessType = BusinessType.INSERT)
    public AjaxResult createSession(@RequestBody CreateSessionRequest request) {
        // 构建用户信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(request.getUserName());
        userInfo.setUserAvatar(request.getUserAvatar());
        
        return customerServiceService.createSession(request.getUserId(), userInfo);
    }
    
    /**
     * 发送消息
     */
    @PostMapping("/message/send")
    @Log(title = "客服消息", businessType = BusinessType.INSERT)
    public AjaxResult sendMessage(@RequestBody SendMessageRequest request) {
        return customerServiceService.sendMessage(
            request.getSessionId(), 
            request.getContent(), 
            request.getMessageType(), 
            request.getUserId()
        );
    }
    
    /**
     * 获取历史消息
     */
    @GetMapping("/messages/history")
    public AjaxResult getHistoryMessages(@RequestParam String sessionId,
                                        @RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "20") int pageSize) {
        return customerServiceService.getHistoryMessages(sessionId, page, pageSize);
    }
    
    /**
     * 检查在线状态
     */
    @GetMapping("/status/online")
    public AjaxResult checkOnlineStatus() {
        return customerServiceService.checkOnlineStatus();
    }
    
    /**
     * 上传图片
     */
    @PostMapping("/upload/image")
    @Log(title = "客服图片上传", businessType = BusinessType.INSERT)
    public AjaxResult uploadImage(@RequestParam String sessionId,
                                 @RequestParam("image") MultipartFile file,
                                 @RequestParam Long userId) {
        try {
            byte[] fileData = file.getBytes();
            String fileName = file.getOriginalFilename();
            
            return customerServiceService.uploadImage(sessionId, fileData, fileName, userId);
        } catch (IOException e) {
            return AjaxResult.error("文件上传失败: " + e.getMessage());
        }
    }
    
    /**
     * AI智能回复
     */
    @PostMapping("/ai/chat")
    public AjaxResult getAIResponse(@RequestParam String message,
                                   @RequestParam String sessionId) {
        try {
            // 这里需要调用服务层的AI方法，但需要先获取上下文
            // 暂时返回一个简单的回复
            String reply = "您好，我是智能客服助手。您说：" + message + "。我会尽力为您提供帮助。";
            return AjaxResult.success("AI回复成功", reply);
        } catch (Exception e) {
            return AjaxResult.error("AI服务调用失败: " + e.getMessage());
        }
    }
    
    /**
     * 关闭会话
     */
    @PostMapping("/session/close")
    @Log(title = "客服会话", businessType = BusinessType.UPDATE)
    public AjaxResult closeSession(@RequestParam String sessionId) {
        return customerServiceService.closeSession(sessionId);
    }
    
    /**
     * 获取会话信息
     */
    @GetMapping("/session/{sessionId}")
    public AjaxResult getSessionInfo(@PathVariable String sessionId) {
        return customerServiceService.getSessionInfo(sessionId);
    }
    
    /**
     * 获取用户活跃会话
     */
    @GetMapping("/session/active/{userId}")
    public AjaxResult getActiveSession(@PathVariable Long userId) {
        return customerServiceService.getActiveSession(userId);
    }
    
    /**
     * 标记消息为已读
     */
    @PostMapping("/message/read/{messageId}")
    public AjaxResult markMessageAsRead(@PathVariable String messageId) {
        return customerServiceService.markMessageAsRead(messageId);
    }
}

// 用户信息内部类
class UserInfo {
    private String userName;
    private String userAvatar;
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getUserAvatar() {
        return userAvatar;
    }
    
    public void setUserAvatar(String userAvatar) {
        this.userAvatar = userAvatar;
    }
}

// 创建会话请求类
class CreateSessionRequest {
    private Long userId;
    private String userName;
    private String userAvatar;
    
    public Long getUserId() {
        return userId;
    }
    
    public void setUserId(Long userId) {
        this.userId = userId;
    }
    
    public String getUserName() {
        return userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    public String getUserAvatar() {
        return userAvatar;
    }
    
    public void setUserAvatar(String userAvatar) {
        this.userAvatar = userAvatar;
    }
}

// 发送消息请求类
class SendMessageRequest {
    private String sessionId;
    private String content;
    private String messageType;
    private Long userId;
    
    public String getSessionId() {
        return sessionId;
    }
    
    public void setSessionId(String sessionId) {
        this.sessionId = sessionId;
    }
    
    public String getContent() {
        return content;
    }
    
    public void setContent(String content) {
        this.content = content;
    }
    
    public String getMessageType() {
        return messageType != null ? messageType : "text";
    }
    
    public void setMessageType(String messageType) {
        this.messageType = messageType;
    }
    
    public Long getUserId() {
        return userId;
    }
    
    public void setUserId(Long userId) {
        this.userId = userId;
    }
}
